package com.hmy.uaa.config;

import com.hmy.uaa.common.security.CustomerUserAuthenticationConverter;
import com.hmy.uaa.common.security.UserNameDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.security.oauth2.authserver.AuthorizationServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import javax.sql.DataSource;
import java.security.KeyPair;
import java.util.ArrayList;
import java.util.Collection;

/**
 * 授权服务器配置
 */
@Configuration
@EnableAuthorizationServer
@EnableConfigurationProperties(AuthorizationServerProperties.class)
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private AuthorizationServerProperties authorizationServerProperties;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private UserNameDetailsService userNameDetailsService;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Bean
    public CustomerUserAuthenticationConverter customerUserAuthenticationConverter() {
        return new CustomerUserAuthenticationConverter();
    }

    @Bean
    public DefaultAccessTokenConverter defaultAccessTokenConverter() {
        DefaultAccessTokenConverter defaultAccessTokenConverter = new CustomerUserAuthenticationConverter();
        // DefaultAccessTokenConverter defaultAccessTokenConverter = new DefaultAccessTokenConverter();
        // defaultAccessTokenConverter.setUserTokenConverter(customerUserAuthenticationConverter());
        return defaultAccessTokenConverter;
    }

    /**
     * 使用非对称加密算法来对Token进行签名
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        AuthorizationServerProperties.Jwt jwtProperties = authorizationServerProperties.getJwt();
        // 导入证书
        KeyPair keyPair = new KeyStoreKeyFactory(
                new ClassPathResource(jwtProperties.getKeyStore()),
                jwtProperties.getKeyPassword().toCharArray()).getKeyPair(jwtProperties.getKeyAlias());
        converter.setKeyPair(keyPair);
        converter.setAccessTokenConverter(defaultAccessTokenConverter());
        return converter;
    }

    @Bean
    public JwtTokenStore jwtTokenStore() {
        // 配置JwtAccessToken转换器
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * 配置OAuth2的客户端相关信息
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    /**
     * 用来配置令牌端点(Token Endpoint)的安全约束.
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer
                // 开启/oauth/token_key验证端口权限访问
                .tokenKeyAccess(authorizationServerProperties.getTokenKeyAccess())
                // 开启/oauth/check_token验证端口认证权限访问
                .checkTokenAccess(authorizationServerProperties.getCheckTokenAccess())
                .allowFormAuthenticationForClients();
    }

    /**
     * 用来配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        Collection<TokenEnhancer> tokenEnhancers = applicationContext.getBeansOfType(TokenEnhancer.class).values();
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); // token 自定义信息
        tokenEnhancerChain.setTokenEnhancers(new ArrayList<>(tokenEnhancers));

        endpoints
                .authenticationManager(authenticationManager)
                .userDetailsService(userNameDetailsService)
                .tokenStore(jwtTokenStore())
                // 刷新token设置为不重复使用
                .reuseRefreshTokens(false)
                .tokenEnhancer(tokenEnhancerChain);
    }

}
